package com.baizhi.controller;

import com.baizhi.entity.Banner;
import com.baizhi.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;
    @RequestMapping("/showPage")
    public @ResponseBody Map showPage(Integer page, Integer limit){
        Map map = bannerService.selectPage(page, limit);
        return map;
    }
    @RequestMapping("/remove")
    public @ResponseBody Map remove(Integer id){
        Map map = new HashMap();
        try{
            bannerService.deleteById(id);
            map.put("status","success");
        }catch(Exception e){
            e.printStackTrace();
            map.put("status","failed");
            map.put("msg","删除异常，请稍后再试");
        }
        return map;
    }
    @RequestMapping("/uploadImg")
    public @ResponseBody Map uploadImg(MultipartFile file, HttpServletRequest request){
        Map map = new HashMap();
        String filename = file.getOriginalFilename();
        ServletContext servletContext = request.getServletContext();
        String realpath = servletContext.getRealPath("/img");
        String path = realpath+"/"+filename;
        try{
            FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(path));
            map.put("status","success");
            map.put("name",filename);
            map.put("path","/img/"+filename);
        }catch (Exception e){
            e.printStackTrace();
            map.put("status","failed");
            map.put("msg","上传失败。请稍后再试");
        }
        return map;
    }

}
